package com.ccb.jyzx.expand.tiantouonline.job;

import com.ccb.jyzx.expand.tiantouonline.bean.*;
import com.ccb.jyzx.expand.tiantouonline.bean.bo.EftLogBo;
import com.ccb.jyzx.expand.tiantouonline.bean.vo.BatchPushVo;
import com.ccb.jyzx.expand.tiantouonline.bean.vo.FileInfoVo;
import com.ccb.jyzx.expand.tiantouonline.service.*;
import com.ccb.jyzx.expand.tiantouonline.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 串任务
 * @projectName: extend
 * @author: jianghaolin
 * @date: 2019/11/21
 * @version: 1.0
 */
@Component
public class ClassifyJob {

    Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BatchInfoService batchInfoService;

    @Autowired
    private FileTagsInfoService fileTagsInfoService;

    @Autowired
    FileInfoService fileInfoService;

    @Autowired
    private BatchPushService batchPushService;

    @Autowired
    private ClassifyService classifyService;

    @Autowired
    private EftLogService eftLogService;

    @Autowired
    private EftTagLogService eftTagLogService;

    @Autowired
    private FileToPdfService fileToPdfService;

    @Autowired
    private PdfToHtmlService pdfToHtmlService;

    @Value("${file_cache_dir}")
    private String file_cache_dir;

    @Value("${file_tag_dir}")
    private String file_tag_dir;

    @Value("${push_tgz_dir}")
    private String push_tgz_dir;

    /**
     * 压缩并推送
     */
    public void send(){
        String nowDay = DateUtils.nowDay();
        String batch = DateUtils.getMorningOrAfternoone();
        //处理本次提交和覆盖的
        compressAndSend(nowDay,batch);
    }

    /**
     * 处理本次提交的压缩并推送
     * @param nowDay
     * @param batch
     */
    private void compressAndSend(String nowDay, String batch){
        List<FileInfoVo> list = batchInfoService.listNoPush();
        if(list != null && list.size() > 0){
            String tagName = "tag_" + nowDay + "_" + batch + ".txt";
            String wordBasePath = file_tag_dir + nowDay + "/" + ConstantUtil.DOC_NAME_PAGE + nowDay + "_" + batch ;
            //生成tag.txt
            classifyService.getTag(wordBasePath + "/" + tagName,"word");
            String htmlBasePath = file_tag_dir + nowDay + "/" + ConstantUtil.HTML_NAME_PAGE + nowDay + "_" + batch;
            //生成tag文件
            classifyService.getTag(htmlBasePath + "/" + tagName,"html");

            String puhshWordlTgz = push_tgz_dir + nowDay + "/" + ConstantUtil.DOC_NAME_PAGE + nowDay + "_" + batch + ".tgz";
            String puhshHtmlTgz = push_tgz_dir + nowDay + "/" + ConstantUtil.HTML_NAME_PAGE + nowDay + "_" + batch + ".tgz";

            EftTagLog tagLog = new EftTagLog();
            String eftTagLogId = IDUtils.createNumId(36);
            tagLog.setId(eftTagLogId);
            List<String> updateBatchInfoIds = new ArrayList<>();
            List<EftLogBo> eftLogBos = new ArrayList<>();
            for(FileInfoVo info : list){
                String opCode = info.getOpCode();
                logger.info("ipCode==========" + opCode);
                if(ConstantUtil.CAN_PUBLISH.equals(opCode)){
                    FileTagsInfo fileTagsInfo = fileTagsInfoService.findByInfoid(info);
                    String frequentness = fileTagsInfo.getTypeId().replace("0","");
                    String reportTime = DateUtils.getYestoday();
                    String batchSeq = batch;
                    Classify classify = new Classify();
                    classify.setFrequentness(frequentness);
                    classify.setReportTime(reportTime);
                    List<BatchPush> pubs = batchPushService.findOneByFileId(info.getId());
                    if(pubs != null && pubs.size() > 0){
                        for(BatchPush pub : pubs){
                            if(pub != null) {
                                classify.setFileSeq(pub.getFileSeq());
                            }
                            classify.setBatchSeq(batchSeq);

                            //获取文件ID
                            String fileId = ClassifyUtils.getFileId(classify);

                            String word = file_cache_dir + info.getSavePath() + info.getFileExten();
                            String html = file_cache_dir + info.getSavePath() + ".html";

                            String wordTarget =  wordBasePath+ "/" + fileId + info.getFileExten();
                            String htmlTarget = htmlBasePath + "/" + fileId + ".html";
                            FileUtils.copyFile(word,wordTarget);
                            FileUtils.copyFile(html,htmlTarget);

                            updateBatchInfoIds.add(info.getBatchInfoId());


                            EftLogBo wordBo = new EftLogBo();
                            wordBo.setWord(word);
                            wordBo.setWordTarget(wordTarget);
                            wordBo.setEftTagLogId(eftTagLogId);
                            eftLogBos.add(wordBo);

                            EftLogBo htmlBo = new EftLogBo();
                            htmlBo.setWord(html);
                            htmlBo.setWordTarget(htmlTarget);
                            htmlBo.setEftTagLogId(eftTagLogId);
                            eftLogBos.add(htmlBo);
                        }
                    }
                }
            }

            //处理覆盖的
            List<BatchPushVo> coverFiles = batchPushService.findAllCoverFiles();
            if(coverFiles != null && coverFiles.size() > 0){
                for(BatchPushVo coverFile : coverFiles){
                    String coverdWord = file_cache_dir + coverFile.getFileName() + coverFile.getFileExten();
                    String coverdHtml = file_cache_dir + coverFile.getFileName() + "html";
                    String coverdWordTarget = wordBasePath + coverFile.getFileName() + coverFile.getFileExten();
                    String coverdHtmlTarget = wordBasePath + coverFile.getFileName() + "html";
                    //copy
                    FileUtils.copyFile(coverdWord,coverdWordTarget);
                    FileUtils.copyFile(coverdHtml,coverdHtmlTarget);


                    updateBatchInfoIds.add(coverFile.getBatchInfoId());


                    EftLogBo wordBo = new EftLogBo();
                    wordBo.setWord(coverdWord);
                    wordBo.setWordTarget(coverdWordTarget);
                    wordBo.setEftTagLogId(eftTagLogId);
                    eftLogBos.add(wordBo);

                    EftLogBo htmlBo = new EftLogBo();
                    htmlBo.setWord(coverdHtml);
                    htmlBo.setWordTarget(coverdHtmlTarget);
                    htmlBo.setEftTagLogId(eftTagLogId);
                    eftLogBos.add(htmlBo);
                }
            }


            //压缩word
            TargzUtil.word2Tgz(wordBasePath,wordBasePath+".tgz");
            //压缩html
            TargzUtil.word2Tgz(htmlBasePath,htmlBasePath+".tgz");

            //推送
            DosUtil.pushTag(wordBasePath + ".tgz",puhshWordlTgz );
            DosUtil.pushTag(htmlBasePath + ".tgz",puhshHtmlTgz );

            tagLog.setSendWordFile(wordBasePath + ".tgz");
            tagLog.setSendHtmlFile(htmlBasePath + ".tgz");
            tagLog.setToHtmlFile(puhshHtmlTgz);
            tagLog.setToWordFile(puhshWordlTgz);
            tagLog.setState(1);
            tagLog.setCreateTime(System.currentTimeMillis());
            eftTagLogService.save(tagLog);
            //更新batchInfo数据为发送状态
            updateSendStates(updateBatchInfoIds);

            //保存日志
            for (EftLogBo bo : eftLogBos){
                saveEftLog(bo);
            }
        }
    }

    /**
     * 批量修改
     * @param ids
     */
    private void updateSendStates(List<String> ids){
        batchInfoService.updateSendStateByids(ids);
    }

    /**
     * 保存eft日志
     * @param bo
     */
    private void saveEftLog(EftLogBo bo){
        String word = bo.getWord();
        String wordTarget = bo.getWordTarget();
        String eftTagLogId = bo.getEftTagLogId();
        logger.info("原先的word：" + word);
        logger.info("copy到的word：" + wordTarget);
        EftLog log = new EftLog();
        log.setId(IDUtils.createNumId(36));
        log.setSendFile(word);
        log.setToFile(wordTarget);
        log.setState(1);
        log.setCreateTime(System.currentTimeMillis());
        log.setTzgLogId(eftTagLogId);
        eftLogService.save(log);
    }

    /**
     * 循环扫描转换
     * 1、查询batchInfo正常的
     * 2、查询对应的文件信息fileInfo
     * 3、
     */
    public void trance(){
        List<FileInfo> list = fileInfoService.findFileinfoUnUnion();
        if(list != null && list.size()>0) {
            for (FileInfo fi : list) {
                String path = fi.getSavePath();
                if(!StringUtils.isEmpty(path)) {
                    long totalSize = fi.getTotalSize();
                    boolean meshFileResult = FileUtils.meshFile(file_cache_dir + path, fi.getFileExten(),totalSize);
                    if(meshFileResult){
                        fileInfoService.updateUpMerged(fi.getId(),1);
                        logger.info("文件合并成功" + new Date(System.currentTimeMillis()));
                        //合并成功后做以下操作，删除源文件夹
                        File deleteFile = new File(file_cache_dir + path);
                        FileUtils.deleteFile(deleteFile);

                        String pathtemp = path.substring(0,path.lastIndexOf("/")) + "/";
                        String filename = path.substring(path.lastIndexOf("/")+1);
                        if("002".equals(fi.getOpCode()) || "003".equals(fi.getOpCode())) {
                            //word转PDF
                            boolean isSuccessWordToPdf = DosUtil.runWordToPdf(file_cache_dir + pathtemp, filename + fi.getFileExten(), file_cache_dir + pathtemp);
                            FileToPdf word = new FileToPdf();
                            String id = fi.getId();
                            String savePath = fi.getSavePath();

                            word.setId(IDUtils.createNumId(36));
                            word.setFileId(id);
                            word.setSavePath(savePath);
                            word.setCreateTime(System.currentTimeMillis());
                            if(isSuccessWordToPdf){
                                word.setState(1);
                            }else{
                                word.setState(0);
                            }
                            try {
                                fileToPdfService.save(word);
                            }catch (SQLException e){
                                logger.error("wor转pdf保存日志失败，时间为：" + new Date(System.currentTimeMillis())
                                + ",出错信息：" + e.getMessage());
                            }
                            if("003".equals(fi.getOpCode())){
                                //PDF转html
                                boolean isSuccessPDF2Html = PDF2Html.pdfToHtml(file_cache_dir + pathtemp+ filename+ ".pdf",file_cache_dir+pathtemp + filename +".html");

                                PdfToHtml pdfToHtml = new PdfToHtml();
                                pdfToHtml.setId(IDUtils.createNumId(36));
                                pdfToHtml.setFileId(id);
                                pdfToHtml.setSavePath(savePath);
                                pdfToHtml.setCreateTime(System.currentTimeMillis());
                                if(isSuccessPDF2Html){
                                    pdfToHtml.setState(1);
                                }else{
                                    pdfToHtml.setState(0);
                                }
                                try {
                                    pdfToHtmlService.save(pdfToHtml);
                                }catch (SQLException e){
                                    logger.error("pdf转html保存日志失败，时间为：" + new Date(System.currentTimeMillis())
                                            + ",出错信息：" + e.getMessage());
                                }


                            }
                        }

                    }else{
                        logger.info("文件合并出错，大小不一样!!!,出错时间：" + new Date(System.currentTimeMillis()));
                    }
                }
            }
        }
    }

    /**
     *  推送测试
     */
    public void push() {
        String tgz = "/home/eft/eft2.3/working/20191122/CCB_WORD_20191122_01.tgz";
        String pt = "/home/ap/dmapp/data/upload/jyzx/20191122/CCB_WORD_20191122_01.tgz";
        DosUtil.pushTag(tgz,pt);
    }

    /**
     *  测试打包
     */
    public void getTgz(){
        String tgzPath = "/home/eft/eft2.3/working/20191122/CCB_WORD_20191122_01";
        String tgzName = "/home/ap/dmapp/data/upload/jyzx/20191122/CCB_WORD_20191122_01.tgz";
        TargzUtil.word2Tgz(tgzPath,tgzName);
    }
}
